import json
import os
from urllib.parse import urljoin

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import  time
import requests
from PIL import Image
from io import BytesIO

# 配置保存路径
SAVE_DIR = "downloaded_images"
os.makedirs(SAVE_DIR, exist_ok=True)

# 打开浏览器
chrome = webdriver.Chrome()
chrome.get('https://fanxing.kugou.com/pcindex/category/8000?action=spreadIndex&id=3')
chrome.maximize_window()

#//div[starts-with(@class,"Grid_gridContainer")]/div[1]/div/div/div/article/a/img/@src
try:
    # 第一次滚动（触发动态加载）
    chrome.execute_script("window.scrollBy(0, 2000);")
    time.sleep(4)  # 等待加载

    # 第二次滚动（可根据需要调整）
    chrome.execute_script("window.scrollBy(0, 4000);")
    time.sleep(4)
    chrome.execute_script("window.scrollBy(0, 6000);")
    time.sleep(4)
    chrome.execute_script("window.scrollBy(0, 8000);")
    time.sleep(4)
    chrome.execute_script("window.scrollBy(0, 10000);")
    time.sleep(4)

    # 显式等待图片容器加载
    wait = WebDriverWait(chrome , 20)
    container  = wait.until(
        EC.visibility_of_element_located((By.XPATH , '//div[@class="fx-category-list"]'))
    )
# 获取所有图片元素
    images = wait.until(EC.presence_of_all_elements_located(
        (By.XPATH, '//div[@class="fx-category-list"]/div[2]/div/div/div[1]/div/img')
    ))

    # 收集所有图片URL
    img_urls = []
    for img in images:
        src = img.get_attribute('src')
        if src:  # 确保不是空链接
            # 处理相对路径
            full_url = urljoin(chrome.current_url, src)
            img_urls.append(full_url)
    # 下载并处理图片
    for index , url in enumerate(img_urls) :
        try :
            response = requests.get(url , stream = True , timeout = 10)
            if response.status_code == 200 :
                # 将内容加载到内存并检测格式
                content = BytesIO(response.content)

                # 尝试用 Pillow 检测图像格式
                try :
                    image = Image.open(content)
                    img_format = image.format  # 获取真实格式（GIF/JPEG/WEBP等）
                except :
                    img_format = "UNKNOWN"  # 未知格式默认处理为 JPG

                # 动态生成文件名和后缀
                if img_format == "GIF" :
                    file_name = f"music-stand-cover{index}.gif"
                else :
                    file_name = f"music-stand-cover{index}.jpg"

                save_path = os.path.join(SAVE_DIR , file_name)

                # 处理非 GIF 格式的转换
                if img_format != "GIF" :
                    try :
                        # 如果是 WebP/PNG 等格式，转换为 JPG
                        if image.mode in ("RGBA" , "P") :
                            image = image.convert("RGB")
                        image.save(save_path , "JPEG" , quality = 90)
                    except :
                        # 如果转换失败，直接保存原始内容（例如未知格式）
                        with open(save_path , "wb") as f :
                            f.write(response.content)
                else :
                    # 直接保存 GIF 原始数据
                    with open(save_path , "wb") as f :
                        f.write(response.content)

                print(f"下载成功：{file_name}")
        except Exception as e :
            print(f"下载失败 {url}: {str(e)}")


finally:
    chrome.quit()
print("所有操作已完成！")


